package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JuYouHuaUtil;
import com.block.datapush.service.apipush.utils.QiDaiAesUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 83  桔柚花  回调
 */
@Service
public class JuYouHuaPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("encryptMobile", mobileMd5);
        bizMap.put("cnName", memberSourceInfo.getRealname());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("amount", JuYouHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", JuYouHuaUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("education", JuYouHuaUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("job", JuYouHuaUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("salaryPay", 1);
        bizMap.put("licenseTime", 0);
        bizMap.put("shebao", JuYouHuaUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("gongjijin", JuYouHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("house", JuYouHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", JuYouHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", JuYouHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("zhima", JuYouHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("creditCard", "0");
        bizMap.put("overdue", JuYouHuaUtil.getyuqi(memberSourceInfo.getYuqi()));

        String aesKey = pushApiKeyParam.getApiKey();
        String body = QiDaiAesUtil.encrypt(JSON.toJSONString(bizMap), aesKey);
        String orgId = pushApiKeyParam.getApiCode();
        Long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", body, orgId, timestamp, aesKey)).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("body", body);


        log.info("【桔柚花】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【桔柚花】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {

            JSONObject data = resultObject.getJSONObject("data");
            String desc = data.getString("desc");
            Integer status = data.getInteger("status");

            pushApiResult.setCode(code + "|" + msg + "|" + status + "|" + desc + "");

            if (StrUtil.equals(String.valueOf(status), "1")) {
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobilePhone", memberSourceInfo.getMobile());
        bizMap.put("cnName", memberSourceInfo.getRealname());
        bizMap.put("idNumber", memberSourceInfo.getIdcard());
        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("amount", JuYouHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTime", JuYouHuaUtil.getloantime(memberSourceInfo.getLoanTime()));
        bizMap.put("loanFor", JuYouHuaUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("education", JuYouHuaUtil.getxueli(memberSourceInfo.getXueli()));
        bizMap.put("job", JuYouHuaUtil.getjob(memberSourceInfo.getGongzuo()));
        bizMap.put("salaryPay", 1);
        bizMap.put("licenseTime", 0);
        bizMap.put("shebao", JuYouHuaUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        bizMap.put("gongjijin", JuYouHuaUtil.getGjj(memberSourceInfo.getGjj()));
        bizMap.put("house", JuYouHuaUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", JuYouHuaUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", JuYouHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("zhima", JuYouHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        bizMap.put("creditCard", "0");
        bizMap.put("overdue", JuYouHuaUtil.getyuqi(memberSourceInfo.getYuqi()));
        bizMap.put("system", "1");
        bizMap.put("ip", memberSourceInfo.getReqIp());

        String aesKey = pushApiKeyParam.getApiKey();
        String body = QiDaiAesUtil.encrypt(JSON.toJSONString(bizMap), aesKey);
        String orgId = pushApiKeyParam.getApiCode();
        Long timestamp = System.currentTimeMillis();
        String sign = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", body, orgId, timestamp, aesKey)).toLowerCase();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("orgId", orgId);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("body", body);

        log.info("【桔柚花】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【桔柚花】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            String desc = data.getString("desc");

            Integer status = data.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                String link = data.getString("link");

                pushApiResult.setOutOrderNo(SecureUtil.md5(memberSourceInfo.getMobileMd5()));
                pushApiResult.setApproveUrl(link);
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(false);
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        log.info("【桔柚花】回调通知【parameterMap】{}【paramContent】{}", JSON.toJSONString(paramContent), paramContent);
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);

        String body = jsonObject.getString("body");

        String result = QiDaiAesUtil.decrypt(body, merchantBaseInfo.getApiKey());
        log.info("【桔柚花】回调通知，揭秘结果【result】{}",  result);

        JSONObject bodyObject = JSON.parseObject(result);

        String phoneMd5 = bodyObject.getString("phoneMd5");
        noticeParamDTO.setOutOrderNo(phoneMd5);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, phoneMd5.toLowerCase());
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    public static void main(String[] args) throws Exception {

        String content = "rgbq9VJNF3Qyc2w2EzPnhHRN9M167Wx9RKw19FM1jmAcI8o1FZcr4vBMG7CTtDRh";

        String result = QiDaiAesUtil.decrypt(content, "l8xmrqbul8xmrqbu");

        System.out.println(result);

    }
    public static void main1(String[] args) {
        Long timestamp = System.currentTimeMillis();
        System.out.println("timestamp = " + timestamp);
        String format = StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", "body", "orgId", timestamp, "aesKey");
        System.out.println("format = " + format);
        String sign = SecureUtil.md5(StrUtil.format("body={}&orgId={}&timestamp={}&secret={}", "body", "orgId", timestamp, "aesKey")).toLowerCase();
        System.out.println("sign = " + sign);
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }




}
